package com.sunday.shoufen.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.UploadUtils;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.common.widgets.MyRatingBar;
import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.shoufen.R;
import com.sunday.shoufen.adapter.GridAdapter;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.entity.Order;
import com.sunday.shoufen.entity.UploadImg;
import com.sunday.shoufen.http.ApiClient;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/10/25.
 */

public class OrderCommentActivity extends BaseActivity {

    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.rightTxt)
    TextView rightTxt;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.common_header)
    RelativeLayout commonHeader;
    @Bind(R.id.shop_img)
    ImageView shopImg;
    @Bind(R.id.shop_title)
    TextView shopTitle;
    @Bind(R.id.price_now)
    TextView priceNow;
    @Bind(R.id.price_old)
    TextView priceOld;
    @Bind(R.id.rating_bar)
    MyRatingBar ratingBar;
    @Bind(R.id.input_num)
    TextView inputNum;
    @Bind(R.id.grid_view)
    NoScrollGridView gridView;
    @Bind(R.id.edit_content)
    ClearEditText editContent;

    private Order order;
    private ArrayList<String> imgList = new ArrayList<>();
    private GridAdapter adapter;
    private long memberId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make_order_comment);
        ButterKnife.bind(this);
        order = (Order) getIntent().getSerializableExtra("order");
        memberId = BaseApp.getInstance().getMember().getId();
        initView();
    }

    private void initView() {
        titleView.setText("评价");
        rightTxt.setText("提交");
        Glide.with(mContext)
                .load(order.getImage())
                .into(shopImg);
        shopTitle.setText(order.getName());
        priceNow.setText("￥" + order.getAmount().setScale(2, RoundingMode.HALF_UP) + "");
        ratingBar.setRating(5, R.drawable.rating_bar,true, 30);

        adapter = new GridAdapter(mContext, imgList);
        gridView.setAdapter(adapter);
        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.img1:
                        int position = (int) v.getTag();
                        if (imgList.size() == position) {
                            selectImg();
                        }
                        break;
                    case R.id.img11:
                        int p = (int) v.getTag();
                        imgList.remove(p);
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        });

        editContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("DefaultLocale")
            @Override
            public void afterTextChanged(Editable s) {
                String content= String.valueOf(s);
                inputNum.setText(TextUtils.isEmpty(content)?"0/300":String.format("%d/300",content.length()));
            }
        });

    }

    private void selectImg() {
        intent = new Intent(mContext, MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        if (imgList != null && imgList.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, imgList);
        }
        startActivityForResult(intent, 0x1111);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        imgList.clear();
        imgList.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));
        adapter.notifyDataSetChanged();
    }


    List<String> netImgs = new ArrayList<>();

    private void uploadImg() {
        showLoadingDialog(0);
        Call<ResultDO<List<UploadImg>>> call = ApiClient.getApiAdapter().uploadImgs(UploadUtils.getRequestBody(imgList));
        call.enqueue(new Callback<ResultDO<List<UploadImg>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<UploadImg>>> call, Response<ResultDO<List<UploadImg>>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    netImgs.clear();
                    if (response.body().getResult()!=null)
                        for (UploadImg img:response.body().getResult()){
                            if (img!=null)
                                netImgs.add(img.getViewUrl());
                        }
                    saveComment();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<UploadImg>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


    private String content;
    private float score;

    @OnClick(R.id.rightTxt)
    void submit() {
        content = editContent.getText().toString().trim();
        score = ratingBar.getRating();
//        if (TextUtils.isEmpty(content)) {
//            ToastUtils.showToast(mContext, "请添加评论内容");
//            return;
//        }

        if (imgList != null && imgList.size() > 0) {
            uploadImg();
        } else {
            saveComment();
        }
    }


    private void saveComment() {
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().commentShop(order.getId(), memberId, content,
                score, StringUtils.listToString(netImgs));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "评论");
                    // EventBus.getDefault().post(new UpdateProMateria());
                    finish();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


}
